using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using DocumentCreationSystem.Services;
using DocumentCreationSystem.Models;

namespace DocumentCreationSystem.Views
{
    /// <summary>
    /// 主题颜色配置对话框
    /// </summary>
    public partial class ThemeConfigDialog : Window
    {
        private readonly ILogger<ThemeConfigDialog> _logger;
        private readonly IThemeService _themeService;
        private readonly List<PresetTheme> _allPresetThemes;
        private List<PresetTheme> _filteredPresetThemes;
        private ThemeConfig _currentTheme;

        public bool IsApplied { get; private set; }

        public ThemeConfigDialog(IServiceProvider serviceProvider)
        {
            try
            {
                InitializeComponent();

                _logger = serviceProvider.GetRequiredService<ILogger<ThemeConfigDialog>>();
                _themeService = serviceProvider.GetRequiredService<IThemeService>();

                _allPresetThemes = _themeService.GetPresetThemes() ?? new List<PresetTheme>();
                _filteredPresetThemes = new List<PresetTheme>(_allPresetThemes);
                _currentTheme = _themeService.GetCurrentTheme() ?? new ThemeConfig();

                InitializeDialog();
            }
            catch (Exception ex)
            {
                // 如果logger还没初始化，使用MessageBox显示错误
                if (_logger != null)
                {
                    _logger.LogError(ex, "初始化主题配置对话框时发生错误");
                }
                MessageBox.Show($"初始化主题配置对话框时发生错误：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);

                // 设置默认值
                _allPresetThemes = new List<PresetTheme>();
                _filteredPresetThemes = new List<PresetTheme>();
                _currentTheme = new ThemeConfig();
            }
        }

        private void InitializeDialog()
        {
            try
            {
                // 设置默认筛选状态
                AllThemesRadio.IsChecked = true;

                // 加载预设主题
                UpdateThemeList();

                // 设置当前主题值
                LoadCurrentTheme();

                _logger.LogInformation("主题配置对话框初始化完成");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "初始化主题配置对话框时发生错误");
                MessageBox.Show("初始化主题配置时发生错误", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void LoadCurrentTheme()
        {
            try
            {
                // 确保 _currentTheme 不为 null
                if (_currentTheme == null)
                {
                    _logger.LogWarning("当前主题为null，使用默认主题");
                    _currentTheme = new ThemeConfig(); // 使用默认值
                }

                // 设置基础主题
                SetBaseThemeRadioButtons(_currentTheme.BaseTheme == "Dark");

                // 设置颜色值
                PrimaryColorTextBox.Text = _currentTheme.PrimaryColor ?? "#2196F3";
                SecondaryColorTextBox.Text = _currentTheme.SecondaryColor ?? "#03DAC6";
                AccentColorTextBox.Text = _currentTheme.AccentColor ?? "#1976D2";

                // 更新颜色预览
                UpdateColorPreviews();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载当前主题时发生错误");
                // 使用默认值
                SetBaseThemeRadioButtons(false); // 默认浅色主题
                PrimaryColorTextBox.Text = "#2196F3";
                SecondaryColorTextBox.Text = "#03DAC6";
                AccentColorTextBox.Text = "#1976D2";
            }
        }

        /// <summary>
        /// 安全地设置基础主题RadioButton状态
        /// </summary>
        private void SetBaseThemeRadioButtons(bool isDark)
        {
            try
            {
                // 先取消事件处理，避免循环触发
                LightThemeRadio.Checked -= BaseTheme_Changed;
                DarkThemeRadio.Checked -= BaseTheme_Changed;

                if (isDark)
                {
                    DarkThemeRadio.IsChecked = true;
                    LightThemeRadio.IsChecked = false;
                }
                else
                {
                    LightThemeRadio.IsChecked = true;
                    DarkThemeRadio.IsChecked = false;
                }

                // 重新绑定事件处理
                LightThemeRadio.Checked += BaseTheme_Changed;
                DarkThemeRadio.Checked += BaseTheme_Changed;
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "设置基础主题RadioButton时发生错误");
            }
        }

        private void PresetTheme_Click(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (sender is FrameworkElement element && element.Tag is PresetTheme presetTheme)
                {
                    // 应用预设主题
                    ApplyPresetTheme(presetTheme);
                    _logger.LogInformation($"选择预设主题: {presetTheme.Name}");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "应用预设主题时发生错误");
                MessageBox.Show("应用预设主题时发生错误", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ApplyPresetTheme(PresetTheme presetTheme)
        {
            try
            {
                if (presetTheme == null)
                {
                    _logger.LogWarning("预设主题为null");
                    return;
                }

                // 设置基础主题
                SetBaseThemeRadioButtons(presetTheme.BaseTheme == "Dark");

                // 设置颜色
                PrimaryColorTextBox.Text = presetTheme.PrimaryColor ?? "#2196F3";
                SecondaryColorTextBox.Text = presetTheme.SecondaryColor ?? "#03DAC6";
                AccentColorTextBox.Text = presetTheme.AccentColor ?? "#1976D2";

                // 设置主题名称
                ThemeNameTextBox.Text = presetTheme.Name ?? "";
                ThemeDescriptionTextBox.Text = presetTheme.Description ?? "";

                // 更新预览
                UpdateColorPreviews();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "应用预设主题时发生错误");
                MessageBox.Show($"应用预设主题时发生错误：{ex.Message}", "错误",
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void BaseTheme_Changed(object sender, RoutedEventArgs e)
        {
            UpdatePreview();
        }

        private void ColorTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            UpdateColorPreviews();
            UpdatePreview();
        }

        private void UpdateColorPreviews()
        {
            try
            {
                // 更新主色调预览
                if (IsValidHexColor(PrimaryColorTextBox.Text))
                {
                    PrimaryColorPreview.Fill = new SolidColorBrush((Color)ColorConverter.ConvertFromString(PrimaryColorTextBox.Text));
                }

                // 更新次要色调预览
                if (IsValidHexColor(SecondaryColorTextBox.Text))
                {
                    SecondaryColorPreview.Fill = new SolidColorBrush((Color)ColorConverter.ConvertFromString(SecondaryColorTextBox.Text));
                }

                // 更新强调色预览
                if (IsValidHexColor(AccentColorTextBox.Text))
                {
                    AccentColorPreview.Fill = new SolidColorBrush((Color)ColorConverter.ConvertFromString(AccentColorTextBox.Text));
                }
            }
            catch (Exception ex)
            {
                _logger?.LogWarning(ex, "更新颜色预览时发生错误");
            }
        }

        private void UpdatePreview()
        {
            try
            {
                // 这里可以实现实时预览功能
                // 暂时只更新预览卡片的样式
                if (PrimaryColorTextBox != null && IsValidHexColor(PrimaryColorTextBox.Text))
                {
                    var primaryColor = (Color)ColorConverter.ConvertFromString(PrimaryColorTextBox.Text);
                    // 可以在这里更新预览卡片的样式
                }
            }
            catch (Exception ex)
            {
                _logger?.LogWarning(ex, "更新预览时发生错误");
            }
        }

        private bool IsValidHexColor(string hexColor)
        {
            if (string.IsNullOrEmpty(hexColor))
                return false;

            try
            {
                if (!hexColor.StartsWith("#"))
                    hexColor = "#" + hexColor;

                ColorConverter.ConvertFromString(hexColor);
                return true;
            }
            catch
            {
                return false;
            }
        }

        private async void Preview_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var themeConfig = CreateThemeConfigFromInput();
                await _themeService.ApplyThemeAsync(themeConfig);
                
                MessageBox.Show("预览已应用！如果不满意，可以点击取消恢复原主题。", "预览", 
                    MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "预览主题时发生错误");
                MessageBox.Show($"预览主题时发生错误：{ex.Message}", "错误", 
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void SaveTheme_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(ThemeNameTextBox.Text))
                {
                    MessageBox.Show("请输入主题名称", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                var themeConfig = CreateThemeConfigFromInput();
                themeConfig.Name = ThemeNameTextBox.Text.Trim();
                themeConfig.Description = ThemeDescriptionTextBox.Text.Trim();
                themeConfig.IsCustom = true;

                // 这里可以实现保存自定义主题的逻辑
                MessageBox.Show("自定义主题保存功能开发中...", "提示", 
                    MessageBoxButton.OK, MessageBoxImage.Information);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存主题时发生错误");
                MessageBox.Show($"保存主题时发生错误：{ex.Message}", "错误", 
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void Apply_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var themeConfig = CreateThemeConfigFromInput();
                await _themeService.ApplyThemeAsync(themeConfig);
                
                IsApplied = true;
                DialogResult = true;
                Close();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "应用主题时发生错误");
                MessageBox.Show($"应用主题时发生错误：{ex.Message}", "错误", 
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void Cancel_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 恢复原主题
                await _themeService.ApplyThemeAsync(_currentTheme);
                DialogResult = false;
                Close();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "恢复原主题时发生错误");
                DialogResult = false;
                Close();
            }
        }

        private async void ResetToDefault_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var result = MessageBox.Show("确定要重置为默认主题吗？", "确认", 
                    MessageBoxButton.YesNo, MessageBoxImage.Question);
                
                if (result == MessageBoxResult.Yes)
                {
                    await _themeService.ResetToDefaultAsync();
                    LoadCurrentTheme();
                    MessageBox.Show("已重置为默认主题", "完成", 
                        MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "重置默认主题时发生错误");
                MessageBox.Show($"重置默认主题时发生错误：{ex.Message}", "错误", 
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private ThemeConfig CreateThemeConfigFromInput()
        {
            return new ThemeConfig
            {
                BaseTheme = DarkThemeRadio.IsChecked == true ? "Dark" : "Light",
                PrimaryColor = PrimaryColorTextBox.Text.Trim(),
                SecondaryColor = SecondaryColorTextBox.Text.Trim(),
                AccentColor = AccentColorTextBox.Text.Trim()
            };
        }

        /// <summary>
        /// 更新主题列表显示
        /// </summary>
        private void UpdateThemeList()
        {
            PresetThemesItemsControl.ItemsSource = _filteredPresetThemes;
        }

        /// <summary>
        /// 主题筛选改变事件
        /// </summary>
        private void ThemeFilter_Changed(object sender, RoutedEventArgs e)
        {
            try
            {
                ApplyThemeFilter();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "筛选主题时发生错误");
            }
        }

        /// <summary>
        /// 主题搜索文本改变事件
        /// </summary>
        private void ThemeSearch_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                ApplyThemeFilter();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "搜索主题时发生错误");
            }
        }

        /// <summary>
        /// 应用主题筛选
        /// </summary>
        private void ApplyThemeFilter()
        {
            if (_allPresetThemes == null)
                return;

            var searchText = ThemeSearchBox?.Text?.Trim().ToLower() ?? "";

            // 根据选择的筛选条件过滤主题
            var filteredThemes = _allPresetThemes.AsEnumerable();

            // 按主题类型筛选
            if (LightThemesRadio?.IsChecked == true)
            {
                filteredThemes = filteredThemes.Where(t => t.BaseTheme == "Light");
            }
            else if (DarkThemesRadio?.IsChecked == true)
            {
                filteredThemes = filteredThemes.Where(t => t.BaseTheme == "Dark");
            }

            // 按搜索文本筛选
            if (!string.IsNullOrEmpty(searchText))
            {
                filteredThemes = filteredThemes.Where(t =>
                    t.Name.ToLower().Contains(searchText) ||
                    t.Description.ToLower().Contains(searchText) ||
                    t.Tags.Any(tag => tag.ToLower().Contains(searchText)));
            }

            _filteredPresetThemes = filteredThemes.ToList();
            UpdateThemeList();
        }
    }
}
